package com.pan.test.service.impl;

import com.pan.test.entity.po.OrderInfo;
import com.pan.test.entity.po.UserInfo;
import com.pan.test.entity.vo.PaymentVO;
import com.pan.test.mappers.OrderMapper;
import com.pan.test.mappers.UserInfoMapper;
import com.pan.test.service.PaymentService;
import com.pan.test.utils.OrderUtils;
import com.pan.test.utils.PaymentUtils;
import com.pan.test.component.RedisComponent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private RedisComponent redisComponent;

    private static final long MB = 1024 * 1024L; // 1MB = 1024 * 1024 bytes

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> createPackageOrder(PaymentVO paymentVO) {
        // 参数验证
        if (paymentVO == null) {
            throw new RuntimeException("支付参数不能为空");
        }
        if (!StringUtils.hasText(paymentVO.getPackageId())) {
            throw new RuntimeException("套餐ID不能为空");
        }
        if (paymentVO.getAmount() == null || paymentVO.getAmount() <= 0) {
            throw new RuntimeException("支付金额不正确");
        }

        // 生成订单ID
        String orderId = OrderUtils.generateOrderId();
        
        try {
            // 保存订单信息到数据库
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrderId(orderId);
            orderInfo.setPackageId(paymentVO.getPackageId());
            orderInfo.setAmount(new BigDecimal(paymentVO.getAmount().toString()));
            // 测试阶段，直接将订单状态设置为已支付
            orderInfo.setStatus(1); 
            orderInfo.setCreateTime(new Date());
            orderInfo.setPayTime(new Date());
            // TODO: 从 Session 或 Token 中获取当前登录用户ID
            String userId = "6146216745";
            orderInfo.setUserId(userId);
            
            // 将订单信息保存到数据库
            orderMapper.insert(orderInfo);
            
            // 更新用户存储空间
            Long additionalSpace = getAdditionalSpaceByPackageId(paymentVO.getPackageId());
            if (additionalSpace > 0) {
                // 获取用户当前信息
                UserInfo userInfo = userInfoMapper.selectByUserId(userId);
                if (userInfo != null) {
                    // 更新用户总空间（转换为字节）
                    userInfoMapper.updateUserSpace(userId, null, additionalSpace * MB);
                    // 重置用户空间使用缓存
                    redisComponent.resetUserSpaceUse(userId);
                }
            }
            
            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("orderId", orderId);
            result.put("status", "success");
            result.put("message", "订单创建成功");
            
            return result;
        } catch (Exception e) {
            throw new RuntimeException("创建订单失败：" + e.getMessage());
        }
    }

    /**
     * 根据套餐ID获取对应的存储空间大小（MB）
     */
    private Long getAdditionalSpaceByPackageId(String packageId) {
        // 根据套餐ID返回对应的存储空间大小
        Map<String, Long> packageSpaceMap = new HashMap<>();
        packageSpaceMap.put("PKG0000001", 10240L);  // 基础套餐 10GB
        packageSpaceMap.put("PKG0000002", 51200L);  // 进阶套餐 50GB
        packageSpaceMap.put("PKG0000003", 102400L); // 专业套餐 100GB
        packageSpaceMap.put("PKG0000004", 10240L);  // 基础年套餐 10GB
        packageSpaceMap.put("PKG0000005", 51200L);  // 进阶年套餐 50GB
        packageSpaceMap.put("PKG0000006", 102400L); // 专业年套餐 100GB
        
        return packageSpaceMap.getOrDefault(packageId, 0L);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handlePaymentCallback(String orderId, String transactionId) {
        // 查询订单
        OrderInfo orderInfo = orderMapper.selectByOrderId(orderId);
        if (orderInfo == null) {
            throw new RuntimeException("订单不存在");
        }
        if (orderInfo.getStatus() != 0) {
            throw new RuntimeException("订单状态异常");
        }
        
        // 更新订单状态为已支付
        orderMapper.updateStatus(orderId, 1);
    }

    @Override
    public Map<String, Object> getPaymentRecords(Integer pageNum, Integer pageSize) {
        // TODO: 实现分页查询
        List<Map<String, Object>> records = new ArrayList<>();
        Map<String, Object> record = new HashMap<>();
        record.put("orderId", "ORDER" + System.currentTimeMillis());
        record.put("packageId", "PKG0000001");
        record.put("packageName", "基础套餐");
        record.put("amount", 9.90);
        record.put("paymentMethod", "alipay");
        record.put("status", 1); // 1: 已支付
        record.put("createTime", new Date());
        record.put("payTime", new Date());
        records.add(record);
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", records);
        result.put("total", 1);
        
        return result;
    }

    @Override
    public Map<String, Object> getCurrentPackage() {
        // TODO: 实现获取当前套餐信息
        Map<String, Object> result = new HashMap<>();
        result.put("packageId", "PKG0000001");
        result.put("packageName", "基础套餐");
        result.put("space", 10240); // MB
        result.put("usedSpace", 1024); // MB
        result.put("expireTime", new Date());
        
        return result;
    }
} 